<?php
defined('IN_TS') or die('Access Denied.');

class dutyAction extends duty{

    /*
     * 首页
     */
    public function index(){
		$signPackage = $this->getSignPackage();
		$cover=SITE_URL.'public/images/logo300.png';
        //dump($GLOBALS);
		if( $GLOBALS['TS_USER']!=''){
			$mylink = '&link='.$GLOBALS['TS_USER']['userid'];
		}
        $page = isset($_GET['page']) ? intval($_GET['page']) : '1';

		$groupid =  intval($_GET['groupid']);
		$orgid =  intval($_GET['orgid']);
		$begintime = trim($_GET['begintime']);
		$endtime = trim($_GET['endtime']);
		$register = trim($_GET['register']);
		$star = trim($_GET['star']);
		$tpl = trim($_GET['tpl']);
		$status = trim($_GET['status']);

		$userid = intval($GLOBALS['TS_USER']['userid']);

		if($begintime){
			if($endtime==''){
				$endtime=date('Y-m-d',time());
			}
		}

		if($endtime){
			if($begintime==''){
				$begintime='2017-10-08';
			}

			$endtime=date('Y-m-d',strtotime($endtime)).' 24:00';
		}



		$str = 'status>-1';


		if($groupid){
			$str = $str." and groupid=".$groupid;
			$group = $this->find('group',array('groupid'=>$groupid));
			$title = $group['groupname'];
		}

		if($star){
			$str = $str." and star=1";
			$title = $title.'精华';
		}

		if($orgid){
			$arrUser= aac('user')->findAll('user_info',array('orgid'=>$orgid),null,'userid');

			$uids='';
			foreach ($arrUser as $v) {
				if($uids==''){
					$uids = $v['userid'];
				}else{
					$uids=$uids.','.$v['userid'];
				}
			}

			$str = $str.' and userid in ('.$uids.")";

			$org = $this->find('user_org',array('orgid'=>$orgid));
			$title = $title.$org['orgname'];
		}

		if($begintime!=''&& $endtime!=''){
			$str =$str.' and begintime>'.strtotime($begintime).' and endtime<'.strtotime($endtime);
			$title = $title.date('ymd',strtotime($begintime)).'-'.date('ymd',strtotime($endtime));
		}

		$str1 = $str.' and status=0';

		if($status){
			$str = $str.' and status=0';
		}

        $url = tsUrl('duty','index',array('groupid'=>$groupid,'orgid'=>$orgid,'begintime'=>$begintime,'star'=>$star,'endtime'=>$endtime,'status'=>$status,'page'=>''));

        $lstart = $page*20-20;


		$arrDuty = $this->findAll('duty',$str,'addtime desc',null,$lstart.',20');
        foreach($arrDuty as $key=>$item){
            $arrDuty[$key]['user'] = aac('user')->getOneUser($item['userid']);
			$arrDuty[$key]['group'] =  aac('group')->getOneGroup($item['groupid']);
			$arrDuty[$key]['address'] = $arrDuty[$key]['group'] ['groupname'];
			if($item['image']){
				$arrDuty[$key]['image'] = explode(',',$item['image']);
			}

			//服务类型
			$arrCate= $this->find('duty_cate',array('cateid'=>$item['cateid']),'catename');
			$arrDuty[$key]['cate'] = $arrCate['catename'];

			// 是否点赞

			$isRecommend = $this->findCount ( 'duty_recommend', array (
				'dutyid' => $item['dutyid'],
				'userid' => $userid
			) );
			$arrDuty[$key]['isrecommend']=$isRecommend;

			//获取评论
			$arrComments = $this->findAll ( 'duty_comment', array (
				'dutyid' => $item['dutyid']
			), 'addtime desc' );

			foreach ( $arrComments as $k => $v ) {
				$arrDuty[$key]['comment'] [] = $v;
				$arrDuty[$key]['comment'][$k]['content'] = tsDecode($v['content']);
				$arrDuty[$key]['comment'][$k] ['user'] = aac ( 'user' )->getOneUser ( $v ['userid'] );
			}
        }


		$noVerify = $this->findCount('duty',$str1);
		$arrGroup = $this->findAll('group','isplace>0 and status<>0','groupid asc');

		$arrGroup1 =  $this->findAll('group','isplace=2 or groupid=1','groupid asc');

		$arrOrg = $this->findAll('user_org');

		$arrCate = $this->findAll('duty_cate',null,'cateid asc');


        $dutyNum = $this->findCount('duty',$str );

        $pageUrl = pagination($dutyNum, 20, $page, $url);

		if($userid){
			//获取我的预约
			$arr1 = 'userid='.$userid.' and status=-1  and begintime<'.time();
			$lastOrder =aac('duty')->find('duty',$arr1,'','begintime desc');

			//获取我最后一次服务
			$lastDuty = aac('duty')->find('duty',array('userid'=>$userid,'status'=>1),'','addtime desc');
			if($lastOrder){
				$mygroupid = $lastOrder['groupid'];
			}else{
				$mygroupid = $lastDuty['groupid'];
			}
		}



//查看有无最新公告

		$arrNotice = aac('article')->find('article','isnotice=1 and addtime>'.strtotime('-3 day'),'','addtime desc');
		if($arrNotice){
			$arrNotice['content'] = tsDecode($arrNotice['content']);
			$arrRead = explode(',',$_COOKIE['read_notice']);
			if($arrNotice['groupid']== 0){
				if($GLOBALS['TS_USER']['groupid']>0&&!in_array($arrNotice['articleid'],$arrRead)){
					$show_notice = $arrNotice;
					$show_notice['noticeid'] = $arrNotice['articleid'];
				}
			}else{
				if($GLOBALS['TS_USER']['groupid']==$arrNotice['groupid']&&!in_array($arrNotice['articleid'],$arrRead)){
					$show_notice = $arrNotice;
					$show_notice['noticeid'] = $arrNotice['articleid'];
				}
			}

		}

//提醒是否愿意担任教练

		if($_SESSION['tsuser']['iscoach'] == 0){
			$count_duty = aac('duty')->findCount('duty',array('userid'=>$_SESSION['tsuser']['userid'],'status'=>1,'cateid'=>1));

		}


		if($register == 1){
			$title = '服务登记';
		}else{
			$title = $title.'服务记录';
		}

		$draft = isset($_GET['draft']) ? $_GET['draft'] : '';
		if($tpl){
			include template('index1');
		}else{
			include template('index');
		}

    }

	/*
     * 预约
     */
	public function order(){
		$signPackage = $this->getSignPackage();
		$cover=SITE_URL.'public/images/logo300.png';
		//dump($GLOBALS);

		$type = intval($_GET['type']);
		$groupid =  intval($_GET['groupid']);
		$next = intval($_GET['next']);
		$userid = intval($GLOBALS['TS_USER']['userid']);
		$arrUser = aac('user')->find('user_info',array('userid'=>$userid));
		$arrGroup = $this->findAll('group','isplace=2 and status<>0','province asc,addtime asc');
		if($next == ''){$next = 0;}
		$day = $next*7;

		if(date('w')==1){
			$day0='this Sunday';
		}else{
			$day0='last Sunday';
		}

		$fromday = strtotime('+'.$day.' day',strtotime($day0));

		if ($groupid ==''){
			if($_SESSION['tsuser']['groupid']==''){
				if($userid != 0){
					$arr1 = 'userid='.$userid.' and groupid<>1';
					$myDuty = $this->findAll('duty',$arr1,'begintime desc',null,1);
					if($myDuty){
						$_SESSION['tsuser']['groupid']=$myDuty[0]['groupid'];
					}else{
						$_SESSION['tsuser']['groupid']=$arrGroup[0]['groupid'];
					}

				}else{
					$_SESSION['tsuser']['groupid']=$arrGroup[0]['groupid'];
				}
			}
			$groupid = $_SESSION['tsuser']['groupid'];
			if($groupid==1){
				$groupid=$arrGroup[0]['groupid'];
			}
		}else{
			$_SESSION['tsuser']['groupid'] = $groupid;
		}

		$group =  aac('group')->find('group',array('groupid'=>$groupid));
		$arrRead = explode(',',$_COOKIE['read_notice']);
		if($group['memo']!=''&&!in_array($groupid,$arrRead)){
			$show_notice['title'] = '本馆值班须知';
			$show_notice['content'] = tsDecode($group['memo']);
			$show_notice['noticeid'] = $groupid;
		}
		$strOpen = explode(',',$group['openday']);
		$group_ban = aac('group')->findAll('group_ban',array('groupid'=>$groupid));
		foreach($group_ban as $v){
			if($v['type']==0){
				$strBan[]=$v['ban_date'];
			}else{
				$strAllow[]=$v['ban_date'];
			}

		}


		//$arr = "cateid=1 and groupid=".$groupid.' and begintime>'.$fromday.' and begintime<'.strtotime('+7 day',$fromday);


		//$arrDuty = $this->findAll('duty',$arr,'begintime desc');
		//foreach($arrDuty as $key=>$item){
			//$arrDuty[$key]['user'] = aac('user')->find('user_info',array('userid'=>$item['userid']));
			//$strGroup =  aac('group')->getOneGroup($item['groupid']);
			//$arrDuty[$key]['address'] = $strGroup['groupname'];
			//$pure_duty = $this->find('duty',array('userid'=>$item['userid'],'cateid'=>1,'status'=>1));
			//$arrDuty[$key]['pure_duty'] = $pure_duty;
	//	}


		//$dutyNum = $this->findCount('duty',$arr );


		$title = '服务预约';
		include template('order');
	}

	public function card(){
		$signPackage = $this->getSignPackage();
		$dutyid =  intval($_GET['dutyid']);
		if($dutyid==''){
			$userid = intval($GLOBALS['TS_USER']['userid']);
			$js = intval($_GET['js']);
			$arrDuty = $this->findAll('duty','userid='.$userid.' and status=1','addtime desc',null,'0,1');
			$dutyid = $arrDuty[0]['dutyid'];
			if($dutyid==''){
				getJson('在微澜图书馆服务并登记过才能打卡，加油哦！',$js);
			}

		}
		$strDuty = $this->getOneDuty($dutyid);


        $count = $this->findCount('duty','status=1 and userid='.$strDuty['userid']);
		$title = $strDuty['user']['username'].'在微澜图书馆完成'.$count.'次服务';
		include template('card');
	}

	public function show(){
		$signPackage = $this->getSignPackage();
		$js = intval($_GET['js']);
		$dutyid =  intval($_GET['dutyid']);
		if(!$dutyid){
				getJson('服务记录不存在！',$js);
		}
		$edit = intval($_GET['edit']);
		$strDuty = $this->getOneDuty($dutyid);
		$strDuty['content']=tsDecode($strDuty['job']);
		$strGroup = $this->findAll('group','isplace>0 and status<>0','groupid asc');
		// 是否点赞
		if($strDuty)
		$arrUser=aac('user')->getOneUser($strDuty['userid']);
		$isRecommend = $this->findCount ( 'duty_recommend', array (
			'dutyid' => $dutyid,
			'userid' => $TS_USER ['userid']
		) );

		$arrCate = $this->findAll('duty_cate',null,'orderid asc');

		if($strDuty['image']){
			$strDuty['image'] = explode(',',$strDuty['image']);
		}
		//服务类型
		$strCate= aac('duty')->find('duty_cate',array('cateid'=>$strDuty['cateid']),'catename');
		$strDuty['cate'] = $strCate['catename'];

		//获取评论
		$arrComments = $this->findAll ( 'duty_comment', array (
			'dutyid' => $dutyid
		), 'addtime desc' );

		foreach ( $arrComments as $k => $v ) {
			$strDuty['comment'] [] = $v;
			$strDuty['comment'][$k]['content'] = tsDecode($v['content']);
			$strDuty['comment'][$k] ['user'] = aac ( 'user' )->getOneUser ( $v ['userid'] );
		}
		$cover=SITE_URL.'public/images/logo300.png';
		$count = $this->findCount('duty','dutyid<='.$dutyid.' and userid='.$strDuty['userid']);
		$title = $strDuty['user']['username'].'在微澜图书馆第'.$count.'次服务';
		include template('show');
	}


	public function exporttext(){
		$groupid = trim($_POST['groupid']);
		$beginyear = trim($_POST['beginyear']);
		$beginmonth = trim($_POST['beginmonth']);
		$beginday = trim($_POST['beginday']);
		$endyear = trim($_POST['endyear']);
		$endmonth = trim($_POST['endmonth']);
		$endday = trim($_POST['endday']);
		$userid = trim($_POST['userid']);

		if($beginyear&&$beginmonth&&$beginday){
			$begindate = $beginyear . "-" . $beginmonth . "-" . $beginday.' 0:00';

		}else{
			$begindate ='2017-10-7';
		}
		if($endyear&&$endmonth&&$endday){
			$enddate = $endyear . "-" . $endmonth . "-" . $endday.' 24:00';
		}else{
			$enddate = date('Y-m-d',time());
		}


		if($groupid!=''){
			$str ='status=1 and addtime>'.strtotime($begindate).' and addtime<'.strtotime($enddate);
			if($userid){
				$str=$str.' and userid='.$userid;
			}
			if($groupid==1){
				$arrGroup1=aac('group')->findAll('group',array('isplace'=>1));
				$arr1 = array();
				foreach($arrGroup1 as $arr){
					$arr1[] = $arr['groupid'];
				}
				$groupids = implode(',',$arr1);
				$str = $str.' and groupid in('.$groupids.')';
				$arrGroup =aac('group')->getOneGroup($groupid);
				$groupname = $arrGroup['groupname'];
			}else{
				$str = $str.' and groupid='.$groupid;
				$arrGroup =aac('group')->getOneGroup($groupid);
				$groupname = $arrGroup['groupname'];
			}
			$filename=$groupname.'服务记录.txt';//要导出的文件的文件名需要加上文件后缀
			//$sql="select userid,groupid,sum(term) as sums,count(1) as counts from ts_duty where ".$str." group by userid";
			$sql="select userid from ts_duty where ".$str." group by userid";
			$arrDuty=$this->db->fetch_all_assoc ( $sql );
			$strGroup =  aac('group')->getOneGroup($groupid);
			$chars='';
			foreach ( $arrDuty as $key => $item ){
				$strUser = aac('user')->getOneUser($item['userid']);
				$strUserDuty = aac('duty')->findAll('duty',$str.' and userid='.$item['userid'],'begintime asc');
				$service =  '在'.$strGroup['groupname'].'服务';
				if($strUser['idcard']!=''&&$strUser['deoffice']==0){
					$sums = 0;
					$counts = count($strUserDuty);
					$service = $service.$counts.'次：';
					foreach($strUserDuty as $k => $v){
						$sums = $sums + $v['term'];
						$service = $service.date('Y年m月d日',$v['begintime']).floatval(number_format(round($v['term']*2)/2,1)).'小时';
						if($k<$counts-1){
							$service = $service.'；';
						}
					}
					$sums=number_format(round($sums*2)/2,1);
					$chars = $chars.$strUser['username'].',';
					$chars = $chars.$strUser['idcard'].',';
					$chars = $chars.$sums.',';
					$chars = $chars.$service."\r\n";
				}
			}

			/*
		$filename=$groupname.'服务记录.txt';//要导出的文件的文件名需要加上文件后缀
		//$sql="select userid,groupid,sum(term) as sums,count(1) as counts from ts_duty where ".$str." group by userid";
		$arrDuty=$this->findAll('duty',$str);
		//$strGroup =  aac('group')->getOneGroup($groupid);
		$chars='';
		foreach ( $arrDuty as $key => $item ){
			$strUser = aac('user')->getOneUser($item['userid']);
			if($strUser['idcard']!=''&&$strUser['deoffice']==0){
				$group = aac('group')->getOneGroup($item['groupid']);
				$service =  $beginyear.'年'.$beginmonth.'月'.date('j',$item['begintime']).'日在'.$group['groupname'].'服务';
				$term = number_format(round($item['term']*2)/2,1);
				$chars = $chars.$strUser['username'].',';
				$chars = $chars.$strUser['idcard'].',';
				$chars = $chars.$term.',';
				$chars = $chars.$service."\r\n";
			}

		}*/

		}else{

			$filename='服务记录('.date('ymd',strtotime($begindate)).'-'.date('ymd',strtotime($enddate)).').txt';//要导出的文件的文件名需要加上文件后缀
			$groups=aac('group')->findAll('group','isplace=2 and province in("北京","上海") or groupid=1 ','groupid asc');
			$chars ='';
			foreach($groups as $g){
				$str ='status=1 and addtime>'.strtotime($begindate).' and addtime<'.strtotime($enddate);
				if($userid){
					$str=$str.' and userid='.$userid;
				}
				if($g['groupid']==1){
					$arrGroup1=aac('group')->findAll('group',array('isplace'=>1));
					$arr1 = array();
					foreach($arrGroup1 as $arr){
						$arr1[] = $arr['groupid'];
					}
					$groupids = implode(',',$arr1);
					$str = $str.' and groupid in('.$groupids.')';
					$strGroup =aac('group')->getOneGroup(1);
				}else{
					$str = $str.' and groupid='.$g['groupid'];
					$strGroup =$g;
				}


				$sql="select userid from ts_duty where ".$str." group by userid";
				$arrDuty=$this->db->fetch_all_assoc ( $sql );

				if($arrDuty){

					$chars=$chars.$strGroup['groupname']."\r\n";

					foreach ( $arrDuty as $key => $item ){
						$strUser = aac('user')->getOneUser($item['userid']);
						$strUserDuty = aac('duty')->findAll('duty',$str.' and userid='.$item['userid'],'begintime asc');
						$service =  '在'.$strGroup['groupname'].'服务';
						if($strUser['idcard']!=''&&$strUser['deoffice']==0){
							$sums = 0;
							$counts = count($strUserDuty);
							$service = $service.$counts.'次：';
							foreach($strUserDuty as $k => $v){
								$sums = $sums + $v['term'];
								$service = $service.date('Y年m月d日',$v['begintime']).floatval(number_format(round($v['term']*2)/2,1)).'小时';
								if($k<$counts-1){
									$service = $service.'；';
								}
							}
							$sums=number_format(round($sums*2)/2,1);
							$chars = $chars.$strUser['username'].',';
							$chars = $chars.$strUser['idcard'].',';
							$chars = $chars.$sums.',';
							$chars = $chars.$service."\r\n";
						}

					}
					$chars = $chars."\r\n\r\n\r\n";
				}

			}
		}


		header('Content-Type: text/x-sql');
		header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Content-Disposition: attachment; filename="' .$filename. '"');

		$is_ie = 'IE';
		if ($is_ie == 'IE') {
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
		} else {
			header('Pragma: no-cache');
			header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		}

		echo $chars;

		exit();
	}



	public function openday(){

		$beginyear = trim($_POST['beginyear']);
		$beginmonth = trim($_POST['beginmonth']);
		$beginday = trim($_POST['beginday']);
		$endyear = trim($_POST['endyear']);
		$endmonth = trim($_POST['endmonth']);
		$endday = trim($_POST['endday']);

		$str='';
		if($beginyear!=''&&$beginmonth!=''&&$beginday!=''&&$endyear!=''&&$endmonth!=''&&$endday!=''){
			$begindate = $beginyear . "-" . $beginmonth . "-" . $beginday;
			$enddate = $endyear . "-" . $endmonth . "-" . $endday;
			$str =$str.' and begintime>'.strtotime($begindate).' and begintime<'.strtotime($enddate);
		}



		//$str = $str." group by userid";
		//Excel表格式,这里简略写了8列
		$letter = array('A','B','C');
		//表头数组
		$tableheader = array('分馆','开馆天数','馆员人数');
		$arrGroup = aac('group')->findAll('group','isplace=2');

		$data=array();
		foreach ( $arrGroup as $key => $item ){

			$sql="select count(DISTINCT day) as days,count(DISTINCT userid) as users from ts_duty where status=1 ".$str." and groupid=".$item['groupid'];
			$arr=$this->db->fetch_all_assoc ( $sql );
			$data[$key]=array($item['groupname'],$arr[0]['days'],$arr[0]['users']);
		}
		$filename='开馆天数统计.xls';
		create_xls($data,$letter,$tableheader,$filename);

		output_xls($data,$filename);
		getJson('操作成功',1,1);
	}

	public function excel(){

		$groupid = trim($_POST['groupid']);
		$orgid = trim($_POST['orgid']);
		$beginyear = trim($_POST['beginyear']);
		$beginmonth = trim($_POST['beginmonth']);
		$beginday = trim($_POST['beginday']);
		$endyear = trim($_POST['endyear']);
		$endmonth = trim($_POST['endmonth']);
		$endday = trim($_POST['endday']);

		$str='';

		if($beginyear!=''&&$beginmonth!=''&&$beginday!=''&&$endyear!=''&&$endmonth!=''&&$endday!=''){
			$begindate = $beginyear . "-" . $beginmonth . "-" . $beginday;
			$enddate = $endyear . "-" . $endmonth . "-" . $endday;
			$str =$str.' and begintime>'.strtotime($begindate).' and begintime<'.strtotime($enddate);
		}
		if($groupid!=''){
			$str = $str.' and groupid='.$groupid;
		}
		if($orgid!=''){
			$arrUser= aac('user')->findAll('user_info',array('orgid'=>$orgid),null,'userid');

			$uids='';
			foreach ($arrUser as $v) {
				if($uids==''){
					$uids = $v['userid'];
				}else{
					$uids=$uids.','.$v['userid'];
				}
			}
			$str = $str.' and userid in ('.$uids.")";
		}

		//$str = $str." group by userid";
		//Excel表格式,这里简略写了8列
		$letter = array('A','B','C','D','E','F','G');
		//表头数组
		$tableheader = array('姓名','身份证号','等级','服务处所','服务时长','服务次数','不导入官方平台');
		//$arrDuty = $this->findAll('duty',$str,null,null,null,null);
		$sql="select userid,groupid,sum(term) as sums,count(1) as counts from ts_duty where status=1 ".$str." group by userid";
		$arrDuty=$this->db->fetch_all_assoc ( $sql );
		$data=array();
		foreach ( $arrDuty as $key => $item ){
			$strUser = aac('user')->getOneUser($item['userid']);
			$strGroup =  aac('group')->getOneGroup($item['groupid']);
			$sums=round($item['sums']*2)/2;
			$idcard = $strUser['idcard'].' ';
			$data[$key]=array($strUser['username'],$idcard,$strUser['rolename'],$strGroup['groupname'],$sums,$item['counts'],$strUser['deoffice']);
		}
		$filename='服务时长统计.xls';
		create_xls($data,$letter,$tableheader,$filename);

		output_xls($data,$filename);
		getJson('操作成功',1,1);
	}


	public function addcomment(){
		$js = intval($_GET['js']);
		$userid = intval($GLOBALS['TS_USER']['userid']);
		if($userid == 0) {
			getJson('请登录后再发表评论',$js);
		}

		$dutyid = trim($_POST['dutyid']);
		$content = trim($_POST['content']);
		$strDuty = $this->getOneDuty($dutyid);

		if($content=='<p><br></p>'||content == ''){
			getJson('内容不能为空',$js);
		}

		$this->create('duty_comment',array(
			'dutyid' => $dutyid,
			'content' => $content,
			'userid' => $userid,
			'addtime' => time()
		));

		$count_comment = $this->findCount('duty_comment',array('dutyid'=>$dutyid));
		$this->update('duty',array('dutyid'=>$dutyid),array('count_comment'=>$count_comment));
		//header("Location:".tsUrl('user','duty',array('id'=>$strDuty['userid'])));

		if($strDuty['userid'] != $userid){

			$msg_userid = '0';
			$msg_touserid = $strDuty['userid'];
			$msg_content = '你的服务记录新增一条评论，快去看看吧^_^ ';
			$msg_tourl = tsUrl('duty','show',array('dutyid'=>$dutyid));
			aac('message')->sendmsg($msg_userid,$msg_touserid,$msg_content,$msg_tourl);

		}
		getJson('操作成功',1,1);
		//tsHeaderUrl(tsUrl('duty','show',array('dutyid'=>$dutyid)));

	}

	public function revert(){
		$arrDuty = $this->findAll('duty');
		foreach ( $arrDuty as $v ){
			if($v['period']==0){
				$term =  round($v['term'],1);
				$period = $term-$v['commute'];
				$this->update('duty',array(
					'dutyid'=>$v['dutyid'],
				),array(
					'term'=>$term,
					'period'=>$period,
				));
			}

		}
	}

	public function updateday(){
		$arrDuty = $this->findAll('duty');
		foreach ( $arrDuty as $v ){
				$this->update('duty',array(
					'dutyid'=>$v['dutyid'],
				),array(
					'day'=>date('Ymd',$v['begintime']),
				));
		}
	}

	/*
     * 后台管理入口
     * */
	public function admin(){

		if($GLOBALS['TS_USER']['isadmin']==1){
			include 'app/'.$GLOBALS['TS_URL']['app'].'/admin.'.$GLOBALS['TS_URL']['app'].'.php';
			$appAdmin = $GLOBALS['TS_URL']['app'].'Admin';
			$newAdmin = new $appAdmin($GLOBALS['db']);
			#$newAdmin->$GLOBALS['TS_URL']['mg']();

			$amg = $GLOBALS['TS_URL']['mg'];
			$newAdmin->$amg();

		}else{
			ts404();
		}
	}


	/*
     * 点赞
     * */
	public function recommend(){

		$userid = intval($GLOBALS['TS_USER']['userid']);

		$strUser = aac('user')->getOneUser($userid);

		$dutyid = intval ( $_POST ['dutyid'] );

		$isRecommend = $this->findCount ( 'duty_recommend', array (
			'dutyid' => $dutyid,
			'userid' => $userid
		) );

		$strDuty = $this->find('duty',array(
			'dutyid'=>$dutyid,
		));

		if ($isRecommend > 0) {
			$this->delete ( 'duty_recommend', array (
				'dutyid' => $dutyid,
				'userid' => $userid
			) );
			// 对积分进行处理
			aac('user') -> doScore('duty', 'recommend', '',$strDuty['userid'],-5);
			aac('user') -> doScore('duty', 'recommend', '',$userid,5);

		}else{


			if ($strUser['count_score']<5) {
				echo 0;
				exit ();
			}

			$this->create ( 'duty_recommend', array (
				'dutyid' => $dutyid,
				'userid' => $userid
			) );

			// 对积分进行处理
			aac('user') -> doScore('duty', 'recommend', '',$strDuty['userid'],5);
			aac('user') -> doScore('duty', 'recommend', '',$userid,-5);

		}


		$count_recommend = $this->findCount ( 'duty_recommend', array (
			'dutyid' => $dutyid
		) );

		$this->update ( 'duty', array (
			'dutyid' => $dutyid
		), array (
			'count_recommend' => $count_recommend
		) );




		if($strDuty['userid'] != $userid){

			$msg_userid = '0';
			$msg_touserid = $strDuty['userid'];
			$msg_content = $GLOBALS['TS_USER']['username'].'赞了你的服务记录，告诉你一声哈^_^ ';
			$msg_tourl = tsUrl('duty','show',array('dutyid'=>$dutyid));
			aac('message')->sendmsg($msg_userid,$msg_touserid,$msg_content,$msg_tourl);

		}
		header("Location:".tsUrl('duty','show',array('dutyid'=>$dutyid)));
		exit ();
	}


	public function sum(){

		$page = isset($_GET['page']) ? intval($_GET['page']) : 1;

		$lstart = $page*20-20;

		$groupid = trim($_GET['groupid']);
		$orgid = trim($_GET['orgid']);
		$begintime = trim($_GET['begintime']);
		$endtime = trim($_GET['endtime']);
		$addyear = trim($_GET['addyear']);

		$strGroup = $this->findAll('group','isplace>0','groupid asc');

		$strOrg = $this->findAll('user_org');


		if($begintime){
			if($endtime==''){
				$endtime=date('Y-m-d',time());
			}
		}

		if($endtime){
			if($begintime==''){
				$begintime='2017-10-08';
			}
		}



		$str='';


		if($groupid!=''){
			$str = $str.' and groupid='.$groupid;
			$group = $this->find('group',array('groupid'=>$groupid));
			$title = $group['groupname'];
		}

		if($orgid!=''){
			$arrUser= aac('user')->findAll('user_info',array('orgid'=>$orgid),null,'userid');

			$uids='';
			foreach ($arrUser as $v) {
				if($uids==''){
					$uids = $v['userid'];
				}else{
					$uids=$uids.','.$v['userid'];
				}
			}
			$str = $str.' and userid in ('.$uids.")";
			$org = $this->find('user_org',array('orgid'=>$orgid));
			$title = $title.$org['orgname'];
		}


		if($begintime!=''&& $endtime!=''){

			$str =$str.' and begintime>'.strtotime($begintime).' and endtime<'.strtotime($endtime);
			$title = $title.date('ymd',strtotime($begintime)).'-'.date('ymd',strtotime($endtime));
		}


		$sql="select userid,groupid,sum(term) as sums,count(1) as counts from ts_duty where status=1 ".$str." group by userid";
		$arrDuty=$this->db->fetch_all_assoc ( $sql );
		$sumNum = 0;
		$countNum =0;
		foreach ( $arrDuty as $key => $item ){
			$strUser = aac('user')->getOneUser($item['userid']);
			if($addyear!=''){
				if($strUser['addtime']>strtotime($addyear.'-1-1')&&$strUser['addtime']<strtotime(($addyear+1).'-1-1')){
					$arrDuty[$key]['user'] = $strUser;
					$arrDuty[$key]['group'] =  aac('group')->find('group',array('groupid'=>$item['groupid']));
					$arrDuty[$key]['sums'] = round($item['sums']*2)/2;
					$sumNum = $sumNum + $arrDuty[$key]['sums'];
					$countNum = $countNum + $arrDuty[$key]['counts'];
				}else{
					unset($arrDuty[$key]);
				}
			}else{
				$arrDuty[$key]['user'] = $strUser;
				$arrDuty[$key]['group'] =  aac('group')->find('group',array('groupid'=>$item['groupid']));
				$arrDuty[$key]['sums'] = round($item['sums']*2)/2;
				$sumNum = $sumNum + $arrDuty[$key]['sums'];
				$countNum = $countNum + $arrDuty[$key]['counts'];
			}

		}

		//按照服务时长排序
		$sort = array_column($arrDuty,'sums');
		array_multisort($sort, SORT_DESC, $arrDuty);


		for($i=$lstart;$i<$lstart+20;$i++){
			if($arrDuty[$i]){
				$strDuty[]=$arrDuty[$i];
			}
		}

		$url = SITE_URL.'index.php?app=duty&ac=sum&groupid='.$groupid.'&orgid='.$orgid.'&begintime='.$begintime.'&endtime='.$endtime.'&addyear='.$addyear.'&page=';


		$dutyNum = count($arrDuty);

		$pageUrl = pagination($dutyNum,20, $page, $url);

		$title= $title.'服务统计';

		if($addyear!=''){
			$title = $title.'('.$addyear.'年注册者）';
		}
		include template('sum');
	}

	function setgroup(){
		$js = intval($_GET['js']);
		$userid = intval($GLOBALS['TS_USER']['userid']);
		if ($userid == 0) {
			getJson('请登录后再操作', $js);
		}
		$dutyid = trim($_POST['dutyid']);
		$groupid = trim($_POST['groupid']);
		$arrDuty = $this->getOneDuty($dutyid);
		if($arrDuty['userid']!=$userid&&$GLOBALS['TS_USER']['isadmin']==0){
			getJson('您没有操作权限', $js);
		}
		$this->update('duty',array('dutyid'=>$dutyid),array('groupid'=>$groupid));
		getJson('重置成功。', 1, 1);
	}

	function resetduty(){
		$arrUser=$this->findAll('user_info','count_duty>0 and lasttime=0');
		foreach($arrUser as $v){

			$duty = $this->find('duty',array('userid'=>$v['userid'],'status'=>1),'','endtime desc');
			if($duty){
				aac('user')->update('user_info',array('userid'=>$v['userid']),array('lasttime'=>$duty['endtime']));
			}
		}
	}

	function delcomment(){
		$js = intval($_GET['js']);
		$commentid = trim($_GET['commentid']);
		$arrComment = $this->find('duty_comment',array('commentid'=>$commentid));
		if($arrComment['userid']!=$GLOBALS['TS_USER']['userid']&&$GLOBALS['TS_USER']['isadmin']==0){
			getJson('您没有操作权限', $js);
		}

		$this->delete('duty_comment',array('commentid'=>$commentid));

		header('location: '.$_SERVER['HTTP_REFERER']);
	}

	/*
 * 预约
 */
	public function chart(){
		$signPackage = $this->getSignPackage();
		$cover=SITE_URL.'public/images/logo300.png';
		$next = intval($_GET['next']);

		$arrGroup = $this->findAll('group','isplace=2 and groupid<>1 and status<>0 and isassist=0','province,city,groupid asc');
		if($next == ''){$next = 0;}
		$day = $next*7;

		if(date('w')==1){
			$day0='this Monday';
		}else{
			$day0='last Monday';
		}

		$fromday = strtotime('+'.$day.' day',strtotime($day0));
		$title = '排班一览表';
		include template('chart');
	}

	public function forbid(){
		$groupid = trim($_POST['groupid']);
		$ban_date = trim($_POST['date']);
		$js = intval($_GET['js']);
		$strGroup = aac('group')->find('group',array('groupid'=>$groupid));
		if($strGroup['userid']!=$GLOBALS['TS_USER']['userid']&&$GLOBALS['TS_USER']['isadmin']==0){
			getJson('您没有操作权限', $js);
		}
		aac('group')->delete('group_ban','groupid='.$groupid.' and ban_date<'.time());
		aac('group')->create('group_ban',array('groupid'=>$groupid,'ban_date'=>$ban_date));
		echo 1;
	}

	public function allow(){
		$groupid = trim($_POST['groupid']);
		$ban_date = trim($_POST['date']);
		$js = intval($_GET['js']);
		$strGroup = aac('group')->find('group',array('groupid'=>$groupid));
		if($strGroup['userid']!=$GLOBALS['TS_USER']['userid']&&$GLOBALS['TS_USER']['isadmin']==0){
			getJson('您没有操作权限', $js);
		}
		aac('group')->delete('group_ban','groupid='.$groupid.' and ban_date<'.time());
		aac('group')->delete('group_ban',array('groupid'=>$groupid,'ban_date'=>$ban_date));
		echo 1;
	}

	public function forbid1(){
		$groupid = trim($_POST['groupid']);
		$ban_date = trim($_POST['date']);
		$js = intval($_GET['js']);
		$strGroup = aac('group')->find('group',array('groupid'=>$groupid));
		if($strGroup['userid']!=$GLOBALS['TS_USER']['userid']&&$GLOBALS['TS_USER']['isadmin']==0){
			getJson('您没有操作权限', $js);
		}
		aac('group')->delete('group_ban','groupid='.$groupid.' and ban_date<'.time());
		aac('group')->delete('group_ban',array('groupid'=>$groupid,'ban_date'=>$ban_date));
		echo 1;
	}

	public function allow1(){
		$groupid = trim($_POST['groupid']);
		$ban_date = trim($_POST['date']);
		$js = intval($_GET['js']);
		$strGroup = aac('group')->find('group',array('groupid'=>$groupid));
		if($strGroup['userid']!=$GLOBALS['TS_USER']['userid']&&$GLOBALS['TS_USER']['isadmin']==0){
			getJson('您没有操作权限', $js);
		}
		aac('group')->delete('group_ban','groupid='.$groupid.' and ban_date<'.time());
		aac('group')->create('group_ban',array('groupid'=>$groupid,'ban_date'=>$ban_date,'type'=>1));
		echo 1;
	}

}